package com.jeeplus.test.jlnu.mailingInfo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionInfoService;
import com.jeeplus.test.jlnu.archivalInfo.domain.entity.ArchParmerter;
import com.jeeplus.test.jlnu.mailingInfo.domain.entity.MailingInfo;
import com.jeeplus.test.jlnu.mailingInfo.domain.vo.MailingInfoVo;
import com.jeeplus.test.jlnu.mailingInfo.service.MailingInfoService;
import com.jeeplus.test.tools.resp.R;
import com.jeeplus.test.website.websiteFile.domain.vo.WebsiteFileReqVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Api(tags = "邮寄信息")
@RestController
@Slf4j
@RequestMapping("/mailingInfo")
public class MailingInfoController {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private AdmissionInfoService admissionInfoService;

    @Autowired
    private MailingInfoService mailingInfoService;
    @ApiOperation("邮寄信息分页查询")
    @GetMapping("/page")
    public Page<MailingInfo> getMailingInfoPage(ArchParmerter mailingInfoReqVo, @RequestParam(defaultValue = "1") int pageNum,
                                                @RequestParam(defaultValue = "10") int pageSize) {
        Page<MailingInfo> page = new Page<>(pageNum, pageSize);
        Page<MailingInfo> pageResult = mailingInfoService.getMailingInfoPage(mailingInfoReqVo, page);
        return pageResult;
    }
    @ApiOperation("根据学号修改邮寄信息")
    @PostMapping("/updateByStuid")
    public R updateByStuid(@RequestBody MailingInfo mailingInfo){
        int i = mailingInfoService.updateByStuid(mailingInfo);
        if(i>0){
            return R.suc();
        }else {
            return R.error();
        }
    }
    @ApiOperation("转递（邮寄）信息新增")
    @PostMapping("/saveMail")
    public R saveMail(@RequestBody List<MailingInfo> mailingInfo){
        for (MailingInfo info : mailingInfo) {
            String studentId = info.getStudentId();
            int count = mailingInfoService.checkStudentId(studentId);
            // 如果当前学号已存在，跳过并继续处理下一条
            if (count > 0) {
               return R.error("9999","已存在当前学号数据 请直接修改");
            }
            int i = mailingInfoService.saveMail(info);
            if (i <= 0) {
                return R.error(); // 如果保存失败直接返回错误
            }
        }

        return R.suc();

    }
    @PostMapping("/mailHtml")
    @ResponseBody
    public void generatePdf(HttpServletResponse response, @RequestBody MailingInfo mailingInfo) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        Map<String, Object> variables = new HashMap<>();
        variables.put("transferNumber", mailingInfo.getArchiveTransferNum());
        variables.put("fileNumber", mailingInfo.getArchivalNum());
        variables.put("receivingCenter", mailingInfo.getReceiveUnitName());
        variables.put("studentName", mailingInfo.getArchiveReceiver());
        variables.put("collegeName", mailingInfo.getAdmissionAcademy());
        variables.put("transferType", mailingInfo.getArchiveTransferSort());
        variables.put("origin", mailingInfo.getSourceArea());
        variables.put("studentPhone", mailingInfo.getPhoneNum());
        variables.put("employmentName", mailingInfo.getEmploymentName());
        variables.put("employmentAddress", mailingInfo.getEmploymentAddress());
        Date sendTime = mailingInfo.getSendTime();
        if(sendTime == null){
            variables.put("receiptYear", "暂无");
            variables.put("receiptMonth", "暂无");
            variables.put("receiptDay", "暂无");
            variables.put("receiptDay", "暂无");
        }else {
            LocalDateTime localDateTime = sendTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

// 分别提取年、月、日
            int year = localDateTime.getYear();
            int month = localDateTime.getMonthValue();
            int day = localDateTime.getDayOfMonth();
            variables.put("receiptYear", year);
            variables.put("receiptMonth", month);
            variables.put("receiptDay", day);
            variables.put("receiptDay", day);
        }

        // 渲染模板
        String html = templateEngine.process("mail", new Context(Locale.CHINA, variables));
        response.getWriter().write(html);
        response.getWriter().flush();
    }

    @PostMapping("/batchUpdate")
    public ResponseEntity<?> batchUpdate(@RequestBody MailingInfoVo mailingInfoVo){
        try{
            boolean success = mailingInfoService.batchUpdate(mailingInfoVo);
            if(success){
                return ResponseEntity.ok().body("批量更新成功");
            }else {
                return ResponseEntity.badRequest().body("批量更新失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }catch (Exception e){
            return ResponseEntity.internalServerError().body("服务器错误: " + e.getMessage());
        }
    }
//    @PostMapping("/saveOrUpdate")
//    public ResponseEntity<Boolean> saveOrUpdateMailing(@RequestPart("mailingInfo") MailingInfo mailingInfo,
//                                                       @RequestPart(value = "file", required = false) MultipartFile file){
//        boolean result = mailingInfoService.saveOrUpdateMailing(mailingInfo,file);
//        return new ResponseEntity<>(result, HttpStatus.OK);
//    }
    @PostMapping("/saveOrUpdate")
    public ResponseEntity<Boolean> saveOrUpdateMailing(@RequestBody MailingInfo mailingInfo
                                                       ){
        boolean result = mailingInfoService.saveOrUpdateMailing(mailingInfo);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
    @PostMapping(value = "/attachment/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Boolean>attachment(
            @PathVariable("id") String id,
            @RequestPart(value = "file", required = true) MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(false); // 文件不能为空
        }
        boolean result = mailingInfoService.attachment(id, file);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
    @GetMapping("/getFileInfo/{id}")
    public ResponseEntity<WebsiteFileReqVo> getFileInfo(@PathVariable("id") String id) {
        try {
            WebsiteFileReqVo websiteFileReqVo = mailingInfoService.getFileInfoByMailingId(id);
            // 无论是否有数据，均返回200状态码，前端根据字段是否为空判断
            return ResponseEntity.ok(websiteFileReqVo);
        } catch (Exception e) {
            log.error("获取文件信息失败", e);
            // 仅当发生非预期异常时返回500错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    @GetMapping("/downloadFile/{id}")
    public void downloadFile(@PathVariable("id") String id, HttpServletResponse response) {
        try {
            // 1. 获取文件数据和文件名
            Map<String, Object> fileInfo = mailingInfoService.getFileByMailingId(id);
            byte[] fileBytes = (byte[]) fileInfo.get("fileBytes");
            String fileName = (String) fileInfo.get("fileName");

            // 2. 设置响应头
            response.setContentType("application/octet-stream");
            // 处理中文文件名编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
                    .replace("+", "%20");  // 替换空格编码
            response.setHeader("Content-Disposition",
                    "attachment; filename*=UTF-8''" + encodedFileName);
            response.setContentLength(fileBytes.length);

            // 3. 写入响应流
            try (var outputStream = response.getOutputStream()) {
                outputStream.write(fileBytes);
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }

    @DeleteMapping("/batchDelete")
    public ResponseEntity <String> delete(String ids){
        String idArray[] = ids.split(",");
        mailingInfoService.removeByIds(Lists.newArrayList ( idArray ) );
        return ResponseEntity.ok("200");
    }
    @GetMapping("/{id}")
    public ResponseEntity<MailingInfoVo> selectMailingById(@PathVariable Long id){
        MailingInfoVo mailingInfoVo = mailingInfoService.selectMailingById(id);
        if(mailingInfoVo == null){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(mailingInfoVo);
    }
    @GetMapping("/list")
    public IPage<MailingInfo> selectAllMailingVOs(
            MailingInfoVo mailingInfoVo,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ){
        Page<MailingInfo> page = new Page<>(pageNum,pageSize);
        Page<MailingInfo> pageResult = mailingInfoService.selectAllMailingVOs(mailingInfoVo,page);
        return pageResult;
    }
    @PostMapping("/DataDowload")
    public ResponseEntity<byte[]> DataDowload(@RequestBody List<String> ids){
        return mailingInfoService.DataDowload(ids);
    }

    //批量移交
    @ApiOperation("批量移交")
    @PostMapping("/batchUpdateMailing")
    public R batchUpdateMailing(@RequestBody MailingInfoVo mailingInfoVo) {
        // 参数校验
        if (CollectionUtils.isEmpty(mailingInfoVo.getTransferStateList())) {
            return R.error("9999", "请选择需要移交的数据");
        }
        mailingInfoService.batchUpdateMailing(mailingInfoVo);
        return R.suc();
    }


}
